package com.hassean.we.admin.app;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Strings;

import com.hassean.we.admin.service.IpphoneSysUserService;
import com.hassean.we.admin.service.IpphoneUserService;
import com.hassean.we.common.constant.CommonConstant;
import com.hassean.we.common.util.Query;
import com.hassean.we.common.util.R;
import com.hassean.we.common.util.template.MD5Util;
import com.hassean.we.common.web.BaseController;
import com.hassean.we.model.entity.IpphoneSysUser;
import com.hassean.we.model.entity.IpphoneUser;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.util.*;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yajun
 * @since 2019-07-01
 */
@RestController
@RequestMapping("app/ipphoneUser")
public class phoneUserController extends BaseController {
    @Autowired private IpphoneUserService ipphoneUserService;
    @Autowired private RedisTemplate<Object,Object> redisTemplate;
    @Autowired private IpphoneSysUserService ipphoneSysUserService;
    /**
    * 通过ID查询
    *
    * @param params
    * @return IpphoneUser
    */
    @RequestMapping("/select/by/id")
    public R<IpphoneUser> get(@RequestBody Map<String, Object> params) {
        Integer id = Integer.parseInt(params.get("id").toString());
        return new R<>(ipphoneUserService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @RequestMapping("/page")
    public R<Map<String, Object>> page(@RequestBody Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        Map<String,Object> resultMap = new HashMap<>();

        if (params.get("page")!=null&&!(params.get("page")).equals("")){
            Integer page = Integer.parseInt(params.get("page").toString());
            params.put("page",page);
        }else{
            Integer page = 1;
            params.put("page",page);
        }

        if (params.get("limit")!=null&&!(params.get("limit")).equals("")){
            Integer limit = Integer.parseInt(params.get("limit").toString());
            System.out.println("limit:"+limit);
        }else{
            Integer limit = 10;
            params.put("limit",limit);
        }
        List< Map<String, Object>> resultList = new ArrayList<>();
        Page<IpphoneUser> page =   ipphoneUserService.selectPage(new Query<>(params), new EntityWrapper<>());
        for (int i = 0; i <page.getRecords().size() ; i++) {
            Map<String,Object>map = new HashMap<>();

            map.put("identity",page.getRecords().get(i).getIdentity());
            map.put("address",page.getRecords().get(i).getAddress());
            map.put("addTime",page.getRecords().get(i).getAddTime());
            map.put("deparmentId",page.getRecords().get(i).getDeparmentId());
            map.put("districts",page.getRecords().get(i).getDistricts());
            map.put("municipalities",page.getRecords().get(i).getMunicipalities());
            map.put("provinces",page.getRecords().get(i).getProvinces());
            map.put("userId",page.getRecords().get(i).getUserId());
            map.put("username",page.getRecords().get(i).getUsername());
            map.put("phone",page.getRecords().get(i).getPhone());
            map.put("sid",page.getRecords().get(i).getSid());
            map.put("townStreet",page.getRecords().get(i).getTownStreet());
            map.put("sex",page.getRecords().get(i).getSex());
            resultList.add(map);

        }


        resultMap.put("total",page.getTotal());//总条数
        resultMap.put("size",page.getSize());//每一页多少条
        resultMap.put("pages",page.getPages());//总页数
        resultMap.put("curren",page.getCurrent());//起始页
        resultMap.put("resultList",resultList);

        return new R<>(resultMap);
    }

    /**
     * 普通用户注册
     * @param  ipphoneUser  实体
     * @return success/false
     */
    @RequestMapping("/register")
    public R<Object> register(@RequestBody IpphoneUser ipphoneUser) {
        R data  =    new R<>();
        Boolean flag = false;
        Map<String,Object> map = new HashMap<>();
        //判断电话号码是否重复
        String  phone= null;
        String username = null;

        if (ipphoneUser.getPhone()!=null){
            EntityWrapper entityWrapper =   new EntityWrapper<>();
            phone =  ipphoneUser.getPhone().toString();
            entityWrapper.eq("phone",phone);
            IpphoneUser phoneUser =  ipphoneUserService.selectOne(entityWrapper);
            if (phoneUser!=null){
                data.setMsg("电话号码已经存在");
                data.setCode(1);
                map.put("token","");
                data.setData(map);
                return data;
            }

        }
        if (ipphoneUser.getUsername()!=null){
            EntityWrapper entityWrapper =   new EntityWrapper<>();
            username =  ipphoneUser.getUsername().toString();
            entityWrapper.eq("username",username);
            IpphoneUser phoneUser =  ipphoneUserService.selectOne(entityWrapper);
            if (phoneUser!=null){
                data.setMsg("用户名已经存在");
                data.setCode(1);
                map.put("token","");
                data.setData(map);
                return data;
            }

        }
        if(ipphoneUser.getUsername()!=null&&ipphoneUser.getPhone()!=null){

            String password = ipphoneUser.getPassword().toString();
            String  userPassword =  DigestUtils.md5Hex(URLEncoder.encode(password));
            //String md5Password = DigestUtils.md5Hex(password);
            ipphoneUser.setPassword(userPassword);

                //生成一个20位的sid
                Date date = new Date();
                String  sid = date.getTime()+"0000";
                ipphoneUser.setSid(sid);
                flag = ipphoneUserService.insert(ipphoneUser);
                String   token =   addToken(phone, password,username);
                data.setMsg("成功");
                data.setCode(0);
                map.put("token",token);
                data.setData(map);
            return data;

        }
        return null;
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @RequestMapping("/delete")
    public R<Boolean> delete(@RequestBody Long id) {
        IpphoneUser ipphoneUser = new IpphoneUser();
        ipphoneUser.setUserId(id);
        ipphoneUser.setUpdateTime(new Date());
        ipphoneUser.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(ipphoneUserService.updateById(ipphoneUser));
    }

    /**
     * 编辑
     * @param  ipphoneUser  实体
     * @return success/false
     */
    @RequestMapping("/edit")
    public  R<Object> edit(@RequestBody IpphoneUser ipphoneUser) {
        ipphoneUser.setUpdateTime(new Date());
        R data  =    new R<>();
        Boolean flag = false;
        String password = ipphoneUser.getPassword().toString();
        String  userPassword =  MD5Util.getMD5String(password);
        ipphoneUser.setPassword(userPassword);
        Long userId = Long.parseLong(ipphoneUser.getUserId().toString());


        //判断用户名是否重复
        EntityWrapper entityWrapper =  new EntityWrapper<>();
        entityWrapper.eq("username",ipphoneUser.getUsername().toString());
        IpphoneUser user  =  ipphoneUserService.selectOne(entityWrapper);
        if (user!=null){
            data.setMsg("用户名已存在");
            data.setCode(1);
            data.setData(flag);
        }else{
            IpphoneUser phoneUser =  ipphoneUserService.selectById(userId);
            if (phoneUser!=null){
                flag = ipphoneUserService.updateById(ipphoneUser);
                data.setMsg("修改成功");
                data.setCode(0);
                data.setData(flag);
            }else{
                data.setMsg("电话号码不存在");
                data.setCode(1);
                data.setData(flag);
            }
        }

        return data;
    }
    @RequestMapping("/getToken")
    public R<Object> getToken() {
        R data  =    new R<>();
        String redisToken  = redisTemplate.opsForValue().get("token").toString();//查询缓存
        data.setCode(0);
        data.setMsg("成功");
        data.setData(redisToken);
        return data;
    }
    /**
     *用户登陆
     */
    @RequestMapping("/login")
    public R<Object> login(@RequestParam Map<String, Object> params) {

        String  phone = null;
        EntityWrapper entityWrapper =   new EntityWrapper<>();
        if(params.containsKey("phone")){
              phone = params.get("phone").toString();
              entityWrapper.eq("phone",phone);
        }
        String password =null;
        if(params.containsKey("password")){
            password = params.get("password").toString();
        }
        String username = null;
        if(params.containsKey("username")){
            username =  params.get("username").toString();
            entityWrapper.eq("username",username);
        }
        R data  =  new R<>();
        data.setMsg("登陆失败");
        data.setCode(1);

        Map<String,Object> map = new HashMap<>();
        entityWrapper.eq("del_flag",0);
        //管理员
        IpphoneSysUser ipphoneSysUser =  ipphoneSysUserService.selectOne(entityWrapper);
        if (ipphoneSysUser!=null){
                String userPassword = ipphoneSysUser.getPassword().toString();
                if (password.equals(userPassword)){
                    String   token =   addToken(phone, password,username);
                    data.setMsg("管理员登陆成功");
                    data.setCode(0);
                    map.put("token",token);

                    map.put("address",ipphoneSysUser.getAddress());
                    map.put("addTime",ipphoneSysUser.getAddTime());
                    map.put("deparmentId","");
                    map.put("districts",ipphoneSysUser.getDistricts());
                    map.put("municipalities",ipphoneSysUser.getMunicipalities());
                    map.put("provinces",ipphoneSysUser.getProvinces());
                    map.put("userId",ipphoneSysUser.getSysUserId());
                    map.put("username",ipphoneSysUser.getUsername());
                    map.put("phone",ipphoneSysUser.getPhone());
                    map.put("sid","");
                    map.put("townStreet",ipphoneSysUser.getTownStreet());
                    map.put("sex",ipphoneSysUser.getSex());
                    map.put("identity",ipphoneSysUser.getIdentity());
                    data.setData(map);
                }else{
                    data.setMsg("登陆失败");
                    data.setCode(1);
                    map.put("token",null);
                    data.setData(map);
                }

            }else{
            //普通用户
            IpphoneUser phoneUser =  ipphoneUserService.selectOne(entityWrapper);
            if (phoneUser!=null){
                String userPassword = phoneUser.getPassword().toString();
                if (password.equals(userPassword)){
                    String   token =   addToken(phone, password,username);
                    data.setMsg("普通用户登陆成功");
                    data.setCode(0);
                    map.put("token",token);
                    map.put("identity",phoneUser.getIdentity());
                    map.put("address",phoneUser.getAddress());
                    map.put("addTime",phoneUser.getAddTime());
                    map.put("deparmentId",phoneUser.getDeparmentId());
                    map.put("districts",phoneUser.getDistricts());
                    map.put("municipalities",phoneUser.getMunicipalities());
                    map.put("provinces",phoneUser.getProvinces());
                    map.put("userId",phoneUser.getUserId());
                    map.put("username",phoneUser.getUsername());
                    map.put("phone",phoneUser.getPhone());
                    map.put("sid",phoneUser.getSid());
                    map.put("townStreet",phoneUser.getTownStreet());
                    map.put("sex",phoneUser.getSex());
                    map.put("identity",phoneUser.getIdentity());
                    data.setData(map);
                }

            }else{
                data.setMsg("登陆失败");
                data.setCode(1);
                map.put("token","");
                data.setData(map);
            }

        }

        return data;
    }

    /**
     *用户退出
     */
    @RequestMapping("/exit")
    public R<Object> exit(@RequestBody Map<String, Object> params) {
        R data  =   new R<>();
        EntityWrapper entityWrapper =   new EntityWrapper<>();
        String  phone = null;
        if(params.containsKey("phone")){
            phone = params.get("phone").toString().trim();
            entityWrapper.eq("phone",phone);
        }

        String username = null;
        if(params.containsKey("username")){
            username =  params.get("username").toString().trim();
            entityWrapper.eq("username",username);
        }

        IpphoneSysUser ipphoneSysUser =  ipphoneSysUserService.selectOne(entityWrapper);
        if(ipphoneSysUser!=null){
            if (ipphoneSysUser!=null){
                String userToken =  redisTemplate.opsForValue().get("token").toString();//查询缓存
                if (!Strings.isNullOrEmpty(userToken)){
                    redisTemplate.delete("token");//删除token
                }
                data.setMsg("退出成功");
                data.setCode(0);

            }else{
                data.setMsg("退出失败");
                data.setCode(1);
            }
        }else{
            IpphoneUser phoneUser =  ipphoneUserService.selectOne(entityWrapper);
            if (phoneUser!=null){
                String userToken =  redisTemplate.opsForValue().get("token").toString();//查询缓存
                if (!Strings.isNullOrEmpty(userToken)){
                    redisTemplate.delete("token");//删除token
                }
                data.setMsg("退出成功");
                data.setCode(0);

            }else{
                data.setMsg("退出失败");
                data.setCode(1);
            }
        }

        return data;
    }

    /**
     * 生成token
     */

    public String addToken(String userPhone,String password,String username){
        //字符串的序列化器
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        //redisTemplate.expire(key,shijian,单位毫秒);设置过期时间
        //token生成规则
        //用户名+密码+当前时间，，用户名+密码MD5加密一次
        String  name = null;
        if(username!=null){
              name =  MD5Util.getMD5String(username);
        }
        String  phone = null;
        if(userPhone!=null){
              phone =  MD5Util.getMD5String(userPhone);
        }

        String  pword =  MD5Util.getMD5String(password);
        Date date =  new Date();
        Long time = date.getTime();
        String token = null;
        if(phone!=null&&username==null){
             token =phone.toString()+pword.toString()+time.toString();
        }
        if(username!=null&&phone==null){
            token = name.toString()+pword.toString()+time.toString();
        }
        if (username!=null&&phone!=null){
            token =phone.toString()+ name.toString()+pword.toString()+time.toString();
        }

        String oldToken = null;
        try {
            oldToken  = redisTemplate.opsForValue().get("token").toString();//查询缓存
            //如果有token就先删除，然后再生成
            if(!Strings.isNullOrEmpty(oldToken)){
                redisTemplate.delete("token");//删除token
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        redisTemplate.opsForValue().set("token",token);//写入缓存
        return token;
    }


    // 加密后解密
    @RequestMapping("/testMD")
    public   static  String JM(String inStr) {
        inStr = "e1a0dc3949ba59abbe56e057f2f0883e";
        char [] a = inStr.toCharArray();
        for  ( int  i =  0 ; i < a.length; i++) {
            a[i] = (char ) (a[i] ^  't' );
        }
        String k = new  String(a);
        return  k;

    }


    // 加密
    @RequestMapping("/MD")
    public    String MD() {


        return DigestUtils.md5Hex(URLEncoder.encode("123456"));
    }

}





